package com.example.dbpage.tool

import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.arch.persistence.room.migration.Migration
import android.content.Context
import com.example.dbpage.bean.Device
import com.example.dbpage.bean.Monery
import com.example.dbpage.bean.Test
import com.example.dbpage.bean.Users


/**
 * Created by zhangfang on 2018/2/9.
 */

@Database(entities = [(Users::class), (Device::class), (Test::class), (Monery::class)], version = 5)
abstract class DaoHelp : RoomDatabase() {

    abstract fun userDao(): UserDao

    abstract fun deviceDao(): DeviceDao

    companion object {

        private var instance: DaoHelp? = null

        fun get(context: Context): DaoHelp {
            if (instance == null) {
                synchronized(DaoHelp::class) {
                    instance = Room.databaseBuilder(context.applicationContext, DaoHelp::class.java, "db2.db")
                            .allowMainThreadQueries()//设置room可以主线程操作
                            .fallbackToDestructiveMigration()
                            .addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5)//升级数据库
                            .build()
                }
            }
            return instance!!
        }

        //升级数据库 1 - 2
        private val MIGRATION_1_2: Migration = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("alter table device add column cartype text")
            }
        }

        //升级数据库 2 - 3
        private val MIGRATION_2_3: Migration = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("alter table device add column carbrand text")
            }
        }

        private val MIGRATION_3_4: Migration = object : Migration(3, 4) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("CREATE TABLE IF NOT EXISTS `test` (`text` TEXT NOT NULL, `code` TEXT NOT NULL, PRIMARY KEY(`text`))")
            }
        }

        private val MIGRATION_4_5: Migration = object : Migration(4, 5) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("CREATE TABLE IF NOT EXISTS `monery` (`monery` INTEGER NOT NULL, PRIMARY KEY(`monery`))")
            }

        }

    }
}